﻿Imports Oracle.DataAccess.Client
Public Class cSaldoCliente
    Private lSaldo As Double = 0
    Private iCliente As cClientes
    Private recovery As String
    ''' <summary>
    ''' si el cliente no existe insertar el registro e inicializar valores en cero
    ''' </summary>
    ''' <param name="idCliente"></param>
    ''' 

    Sub New(ByVal idCliente As String, ByVal Sucursal As Int16)
        iCliente = New cClientes(idCliente)
        iCliente.SeekClienteBySucursal(Sucursal)
        Using conn As OracleConnection = New OracleConnection(My.Settings.ConnectionString)
            Using cmd As OracleCommand = conn.CreateCommand
                cmd.CommandText = "SELECT CAR_SALDOCLIENTE(:PIDCLIENTE,:PSUCURSAL) FROM DUAL"
                cmd.Parameters.Add("PIDCLIENTE", OracleDbType.Varchar2).Value = idCliente
                cmd.Parameters.Add("PSUCRSAL", OracleDbType.Int16).Value = Sucursal
                Try
                    conn.Open()
                    lSaldo = cGeneral.NZ(cmd.ExecuteScalar)
                    conn.Close()
                Catch ex As Exception
                    Throw ex
                End Try
            End Using
        End Using
    End Sub
    Public ReadOnly Property SaldoCliente() As Double
        Get
            Return lSaldo
        End Get
    End Property
    Public ReadOnly Property CupoCliente() As Double
        Get
            Return iCliente.Cupo
        End Get
    End Property
    Public ReadOnly Property Disponible() As Double
        Get
            Return iCliente.Cupo - lSaldo
        End Get
    End Property
End Class

Public Class cRecibos
    Private lDsRecibo As dsCartera
    Private lDsMovi As dsMovimiento
    Private lDsConsMovi As dsConsultaMovimi
    Private lDocumento As String
    Private lIdDocFactura As String
    Private lNumeroFactura As Integer
    Private lNumero As Integer
    Private iTipoDocRecibo As cTipoDocumento
    Private iTipoDocFactura As cTipoDocumento
    Private lbValorRecibo As Decimal
    Private drMov As dsMovimiento.MOV_MOVIMIENTORow
    Private daReciCaja As lbGlobalcom.dsCarteraTableAdapters.CAR_RECIBOSCAJATableAdapter
    Private daReciCajaFac As lbGlobalcom.dsCarteraTableAdapters.CAR_RECIBOCAJADETALLEFACTURATableAdapter
    Private daReciMedioPago As lbGlobalcom.dsCarteraTableAdapters.CAR_RECIBOCAJAMEDIOPAGOTableAdapter

    Private drCaja As dsCartera.CAR_RECIBOSCAJARow = Nothing
    Private drCajaDetalle As dsCartera.CAR_RECIBOCAJADETALLEFACTURARow = Nothing
    Private drCajaMedioPago As dsCartera.CAR_RECIBOCAJAMEDIOPAGORow = Nothing

    Private daMoviDescuento As lbGlobalcom.dsMovimientoTableAdapters.MOV_MOVIMIENTOTableAdapter
    Private daConcepto As lbGlobalcom.dsCarteraTableAdapters.CAR_CONCEPTOPAGOTableAdapter
    ' Private daFactura As lbGlobalcom.dsMovimientoTableAdapters.MOV_MOVIMIENTOTableAdapter
    Public Property mIdDocFactura() As String
        Get
            Return lIdDocFactura
        End Get
        Set(ByVal value As String)
            lIdDocFactura = value
        End Set
    End Property

    Public Property mNumeroFactura() As Integer
        Get
            Return lNumeroFactura
        End Get
        Set(ByVal value As Integer)
            lNumeroFactura = value
        End Set
    End Property

    Public Sub New(ByVal dsMovi As dsMovimiento, ByVal dsConsMovi As dsConsultaMovimi, ByVal docRecibo As String)
        lDsMovi = dsMovi
        lDsConsMovi = dsConsMovi
        lDsRecibo = New dsCartera
        iTipoDocRecibo = New cTipoDocumento(docRecibo)
        lbValorRecibo = valorRecibo()
        drMov = lDsMovi.MOV_MOVIMIENTO.Rows(0)
        iTipoDocFactura = New cTipoDocumento(drMov.IDDOCUMENTO)
        daReciCaja = New lbGlobalcom.dsCarteraTableAdapters.CAR_RECIBOSCAJATableAdapter
        daReciCajaFac = New lbGlobalcom.dsCarteraTableAdapters.CAR_RECIBOCAJADETALLEFACTURATableAdapter
        daReciMedioPago = New lbGlobalcom.dsCarteraTableAdapters.CAR_RECIBOCAJAMEDIOPAGOTableAdapter
        daConcepto = New lbGlobalcom.dsCarteraTableAdapters.CAR_CONCEPTOPAGOTableAdapter
    End Sub
    Public Sub New(ByVal dsConsMovi As dsConsultaMovimi)
        lDsConsMovi = dsConsMovi
    End Sub

    Public Sub New(ByVal dscar As lbGlobalcom.dsCartera, ByVal doc As String, ByVal num As Integer)
        lDsRecibo = dscar
        lDocumento = doc
        lNumero = num
    End Sub

    Public Sub AfectaFacturas()
        Dim conn As OracleConnection = New OracleConnection(My.Settings.ConnectionString)
        Dim cmd As OracleCommand = conn.CreateCommand
        cmd.CommandText = "CAR_AFECTASALDOFACTURAS"
        cmd.CommandType = CommandType.StoredProcedure
        Try
            Dim ltipodoc As String = "", lnumero As Integer
            For Each ldrRecCaja As dsCartera.CAR_RECIBOSCAJARow In lDsRecibo.CAR_RECIBOSCAJA.Rows
                Select Case ldrRecCaja.RowState
                    Case DataRowState.Added, DataRowState.Modified
                        ltipodoc = ldrRecCaja("IDDOCUMENTO", DataRowVersion.Current).ToString.Trim
                        lnumero = ldrRecCaja("NUMERO", DataRowVersion.Current).ToString.Trim
                    Case DataRowState.Deleted
                        ltipodoc = ldrRecCaja("IDDOCUMENTO", DataRowVersion.Original).ToString.Trim
                        lnumero = ldrRecCaja("NUMERO", DataRowVersion.Original).ToString.Trim
                    Case Else
                        ltipodoc = ldrRecCaja("IDDOCUMENTO", DataRowVersion.Current).ToString.Trim
                        lnumero = ldrRecCaja("NUMERO", DataRowVersion.Current).ToString.Trim
                End Select


                cmd.Parameters.Add("PIDDOCUMENTO", OracleDbType.Varchar2).Value = ltipodoc
                cmd.Parameters.Add("PNUMERO", OracleDbType.Int32).Value = lnumero
                cmd.Parameters.Add("PIDDOCFACTURA", OracleDbType.Varchar2)
                cmd.Parameters.Add("PNUMEROFACTURA", OracleDbType.Int32)
                cmd.Parameters.Add("PABONO", OracleDbType.Double)
                cmd.Parameters.Add("PNITEM", OracleDbType.Int32)
                cmd.Parameters.Add("PTIPOACCION", OracleDbType.Int32)
                conn.Open()
                For Each ldrRecFactura As dsCartera.CAR_RECIBOCAJADETALLEFACTURARow In lDsRecibo.CAR_RECIBOCAJADETALLEFACTURA.Rows
                    Select Case ldrRecFactura.RowState
                        Case DataRowState.Added, DataRowState.Modified
                            cmd.Parameters("PIDDOCFACTURA").Value = ldrRecFactura("IDDOCFACTURA")
                            cmd.Parameters("PNUMEROFACTURA").Value = ldrRecFactura("NUMEROFACTURA")
                            cmd.Parameters("PABONO").Value = ldrRecFactura("VALORPAGO")
                            cmd.Parameters("PNITEM").Value = ldrRecFactura("NITEM")
                            cmd.Parameters("PTIPOACCION").Value = 1
                            cmd.ExecuteNonQuery()
                        Case DataRowState.Deleted
                            cmd.Parameters("PIDDOCFACTURA").Value = ldrRecFactura("IDDOCFACTURA", DataRowVersion.Original).ToString.Trim
                            cmd.Parameters("PNUMEROFACTURA").Value = ldrRecFactura("NUMEROFACTURA", DataRowVersion.Original).ToString.Trim
                            cmd.Parameters("PABONO").Value = ldrRecFactura("VALORPAGO", DataRowVersion.Original).ToString.Trim * -1
                            cmd.Parameters("PNITEM").Value = ldrRecFactura("NITEM", DataRowVersion.Original).ToString.Trim
                            cmd.Parameters("PTIPOACCION").Value = 2
                            cmd.ExecuteNonQuery()
                        Case Else
                    End Select
                Next
                conn.Close()
            Next
        Catch ex As Exception
            cError.SalvaError(ex, "Samuel")
            Throw ex
        End Try
    End Sub

    Public Sub cargarMediosPago()
        Dim conn As OracleConnection = New OracleConnection(My.Settings.ConnectionString)
        Dim cmd As OracleCommand
        Try
            cmd = conn.CreateCommand
            cmd.CommandText = "SELECT IDMEDIOPAGO,DESCRIPCION FROM GLO_MEDIOSPAGO"
            conn.Open()
            lDsConsMovi.TBRECIBOCAJAMEDIOPAGO.Load(cmd.ExecuteReader)
        Catch ex As Exception
            Throw ex
        Finally
            conn.Close()
        End Try
    End Sub

    Public Sub cargarRecibo()
        Try
            lDsRecibo.CAR_RECIBOCAJADETALLEFACTURA.Rows.Clear()
            lDsRecibo.CAR_RECIBOSCAJA.Rows.Clear()
            daReciCaja = New lbGlobalcom.dsCarteraTableAdapters.CAR_RECIBOSCAJATableAdapter
            daReciCajaFac = New lbGlobalcom.dsCarteraTableAdapters.CAR_RECIBOCAJADETALLEFACTURATableAdapter
            daReciCaja.FillByIdDocumento(lDsRecibo.CAR_RECIBOSCAJA, lDocumento, lNumero)
            daReciCajaFac.FillByIdDocumento(lDsRecibo.CAR_RECIBOCAJADETALLEFACTURA, lDocumento, lNumero)
        Catch ex As Exception
            cError.SalvaError(ex, "Samuel")
            Throw ex
        End Try
    End Sub

    Public Function agregarDescuento(ByVal totalfactura As Decimal, ByVal tipo As Integer) As Decimal
        Dim descuento As Decimal
        Dim dias As Integer
        Dim valordescuento As Decimal = 0
        Try
            daMoviDescuento = New dsMovimientoTableAdapters.MOV_MOVIMIENTOTableAdapter
            dias = daMoviDescuento.GetDiasFormaPago(mIdDocFactura, mNumeroFactura)
            descuento = daMoviDescuento.GetDescuentoFormaPago(mIdDocFactura, mNumeroFactura)
            Dim dtFactu As New lbGlobalcom.dsMovimiento.MOV_MOVIMIENTODataTable
            dtFactu = daMoviDescuento.GetDataByIdDocumentoNumero(mIdDocFactura, mNumeroFactura)
            If dtFactu.Count > 0 Then
                Dim drFactu As dsMovimiento.MOV_MOVIMIENTORow = dtFactu.Rows(0)
                If drFactu IsNot Nothing Then
                    valordescuento = (drFactu("VALORBASE") + drFactu("VALORIVA")) * descuento
                    If tipo = 0 Then
                        'Dim fechaDoc As Date = drFactu("FECHADOCUMENTO")
                        Dim fechaVen As Date = drFactu("FECHAVENCIMIENTO")
                        'fechaDoc = fechaDoc.AddDays(dias)
                        If fechaVen >= Date.Now Then
                            Dim row As lbGlobalcom.dsCartera.CAR_RECIBOCAJADETALLEFACTURARow
                            row = lDsRecibo.CAR_RECIBOCAJADETALLEFACTURA.NewRow
                            daConcepto = New lbGlobalcom.dsCarteraTableAdapters.CAR_CONCEPTOPAGOTableAdapter
                            row("IDCONCEPTOPAGO") = daConcepto.GetIdSubClase(12)
                            row("IDDOCUMENTO") = lDocumento
                            row("NUMERO") = lNumero
                            row("IDDOCFACTURA") = mIdDocFactura
                            row("NUMEROFACTURA") = mNumeroFactura
                            'row("VALORFACTURA") = drFactu("VALORBASE") + drFactu("VALORIVA")
                            'row("SALDO") = drFactu("SALDO")
                            row("VALORPAGO") = valordescuento
                            row("NITEM") = -1
                            lDsRecibo.CAR_RECIBOCAJADETALLEFACTURA.Rows.Add(row)
                        End If
                    End If
                End If
            End If
            Return valordescuento
            'daMoviDescuento.
        Catch ex As Exception
            cError.SalvaError(ex, "Samuel")
            Throw ex


        End Try
    End Function


    Public Function generaRecibo() As String
        Try
            Dim Recibo As String = ""
            If drMov.SALDO > 0 Then
                If drMov.SALDO >= lbValorRecibo Then
                    drCaja = Nothing
                    drCajaDetalle = Nothing
                    drCajaMedioPago = Nothing
                    encabezadoRecibo()
                    detalleRecibo()
                    medioPagoRecibo()
                    salvaCambiosRecibo()
                    actualizaSaldoFactura()
                    Recibo = drCaja.IDDOCUMENTO + "-" + drCaja.NUMERO.ToString
                    Return Recibo
                Else
                    Return "El valor total de los pagos sobrepasa el Saldo del Documento"
                End If
            Else
                Return "Saldo del documento es Igual a Cero"
            End If
        Catch ex As Exception
            cError.SalvaError(ex, "Henry")
            Throw ex
        End Try
    End Function

    Private Sub encabezadoRecibo()
        Try
            drCaja = lDsRecibo.CAR_RECIBOSCAJA.NewCAR_RECIBOSCAJARow
            drCaja.IDDOCUMENTO = iTipoDocRecibo.TipoDoc
            drCaja.NUMERO = Consec.GetNumeroActual(iTipoDocRecibo.TipoDoc, iTipoDocRecibo.DocEs)
            drCaja.FECHA = Date.Today
            drCaja.IDTERCERO = drMov.IDTERCERO
            drCaja.SUCURSAL = drMov.SUCURSAL
            drCaja.IDCAJA = drMov.IDCAJA
            drCaja.VALORRECIBO = lbValorRecibo
            lDsRecibo.CAR_RECIBOSCAJA.AddCAR_RECIBOSCAJARow(drCaja)
        Catch ex As Exception
            cError.SalvaError(ex, "Henry")
            Throw ex
        End Try
    End Sub

    Private Sub detalleRecibo()
        Dim linea As Integer = 1
        Try
            drCajaDetalle = lDsRecibo.CAR_RECIBOCAJADETALLEFACTURA.NewCAR_RECIBOCAJADETALLEFACTURARow
            drCajaDetalle.IDDOCUMENTO = drCaja.IDDOCUMENTO
            drCajaDetalle.NUMERO = drCaja.NUMERO
            drCajaDetalle.NITEM = linea
            drCajaDetalle.IDDOCFACTURA = drMov.IDDOCUMENTO
            drCajaDetalle.NUMEROFACTURA = drMov.NUMERO
            drCajaDetalle.VALORPAGO = lbValorRecibo
            drCajaDetalle.IDCONCEPTOPAGO = daConcepto.GetIdSubClase(iTipoDocFactura.DocEs)
            lDsRecibo.CAR_RECIBOCAJADETALLEFACTURA.AddCAR_RECIBOCAJADETALLEFACTURARow(drCajaDetalle)
        Catch ex As Exception
            cError.SalvaError(ex, "Henry")
        End Try
    End Sub

    Private Sub medioPagoRecibo()
        Try
            For Each drMedioPago As dsConsultaMovimi.TBRECIBOCAJAMEDIOPAGORow In lDsConsMovi.TBRECIBOCAJAMEDIOPAGO.Rows
                If drMedioPago.VALORPAGO > 0 Then
                    drCajaMedioPago = lDsRecibo.CAR_RECIBOCAJAMEDIOPAGO.NewCAR_RECIBOCAJAMEDIOPAGORow
                    drCajaMedioPago.IDDOCUMENTO = drCaja.IDDOCUMENTO
                    drCajaMedioPago.NUMERO = drCaja.NUMERO
                    drCajaMedioPago.IDMEDIOPAGO = drMedioPago.IDMEDIOPAGO
                    'If drMedioPago.NUMEROMEDIO IsNot DBNull.Value Then
                    '    drCajaMedioPago.NUMEROMEDIO = drMedioPago.NUMEROMEDIO
                    'End If
                    drCajaMedioPago.VALORPAGO = drMedioPago.VALORPAGO
                    lDsRecibo.CAR_RECIBOCAJAMEDIOPAGO.AddCAR_RECIBOCAJAMEDIOPAGORow(drCajaMedioPago)
                End If
            Next
        Catch ex As Exception
            cError.SalvaError(ex, "Henry")
        End Try

    End Sub

    Private Function valorRecibo() As Decimal
        Dim valorTotal As Decimal = 0
        Try
            For Each dr As dsConsultaMovimi.TBRECIBOCAJAMEDIOPAGORow In lDsConsMovi.TBRECIBOCAJAMEDIOPAGO.Rows
                valorTotal += dr.VALORPAGO
            Next
            Return valorTotal
        Catch ex As Exception
            cError.SalvaError(ex, "Henry")
        End Try
    End Function
    Private Sub salvaCambiosRecibo()
        Try
            daReciCaja.Update(lDsRecibo.CAR_RECIBOSCAJA)
            daReciCajaFac.Update(lDsRecibo.CAR_RECIBOCAJADETALLEFACTURA)
            daReciMedioPago.Update(lDsRecibo.CAR_RECIBOCAJAMEDIOPAGO)
        Catch ex As Exception
            cError.SalvaError(ex, "Henry")
            Throw ex
        End Try
    End Sub

    Public Sub actualizaSaldoFactura()
        Dim conn As OracleConnection = New OracleConnection(My.Settings.ConnectionString)
        Dim cmd As OracleCommand = conn.CreateCommand
        cmd.CommandText = "MOV_ACTUALIZASALDOFACTURA"
        cmd.CommandType = CommandType.StoredProcedure
        Try
            cmd.Parameters.Add("PDOCUMENTO", OracleDbType.Varchar2).Value = drMov.IDDOCUMENTO
            cmd.Parameters.Add("PNUMERO", OracleDbType.Int32).Value = drMov.NUMERO
            cmd.Parameters.Add("PVALORRECIBO", OracleDbType.Decimal).Value = lbValorRecibo
            conn.Open()
            cmd.ExecuteNonQuery()
        Catch ex As Exception
            Throw ex
        Finally
            conn.Close()
        End Try
    End Sub

End Class

Public Class cNotasCredito
    Private lDsMov As dsMovimiento
    Private lDocumento As String
    Private lNumero As Integer
    Private daMovimiento As lbGlobalcom.dsMovimientoTableAdapters.MOV_MOVIMIENTOTableAdapter
    Public Sub New(ByVal dsmovi As dsMovimiento, ByVal doc As String, ByVal num As Integer)
        lDsMov = dsmovi
        lDocumento = doc
        lNumero = num
        Totaliza()
    End Sub

    Public Sub cargarNotaCredito()
        Try
            daMovimiento = New lbGlobalcom.dsMovimientoTableAdapters.MOV_MOVIMIENTOTableAdapter
            daMovimiento.FillByIdDocumentoNumero(lDsMov.MOV_MOVIMIENTO, lDocumento, lNumero)
        Catch ex As Exception
            cError.SalvaError(ex, "Samuel")
            Throw ex
        End Try
    End Sub

    Private Sub Totaliza()
        If lDsMov.MOV_MOVIMIENTO.Rows.Count > 0 Then
            Dim drEnc As dsMovimiento.MOV_MOVIMIENTORow = lDsMov.MOV_MOVIMIENTO.Rows(0)
            drEnc.SALDO = cGeneral.NZ(drEnc("VALORBASE")) + cGeneral.NZ(drEnc("VALORIVA"))
        End If
    End Sub
End Class